package com.homson.coreservice.serviceinfrastructure.datasource.repository.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.homson.coreservice.servicecommon.enumeration.ValidStatus;
import com.homson.coreservice.serviceinfrastructure.datasource.model.user.UserDO;
import com.homson.coreservice.serviceinfrastructure.datasource.repository.BaseRepository;
import com.homson.coreservice.serviceinfrastructure.datasource.mapper.UserMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author: homson_leo
 * @contact: hey_超级巨星（Homson_Leo）- 刘泓岑 1196816884@qq.com
 * @time: 2025/10/4 10:59 AM
 **/
@Repository
@Transactional
public class UserRepository extends BaseRepository<UserMapper, UserDO> {
    
    // 添加用户
    public void createOrUpdate(UserDO userDO) {
        LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserDO::getUserId, userDO.getUserId())
                .eq(UserDO::getStatus, ValidStatus.VALID.name());
        List<UserDO> userDOS = list(wrapper);
        if(!CollectionUtils.isEmpty(userDOS)){
            userDO.setId(userDOS.iterator().next().getId());
        }
        userDO.createTime();
        userDO.updateTime();
        userDO.setStatus(ValidStatus.VALID.name());
        this.saveOrUpdate(userDO);
    }
    
    public UserDO findUserById(Long userId) {
        LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserDO::getUserId, userId)
                .eq(UserDO::getStatus, ValidStatus.VALID.name());
        return getOne(wrapper);
    }
}
